package com.frp.lib.utils;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Created by hujianjun on 11/23 0023.
 */
public class NettyUtils {
    //control connection
    public static Channel connect(String host, int port, final ChannelHandler... handlers) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.TCP_NODELAY, true);
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    if (null == handlers) return;
                    p.addLast(handlers);
                }
            });
            // Start the connection attempt.
            ChannelFuture channelFuture = b.connect(host, port).sync();
            if (!channelFuture.isSuccess()) {
                throw new RuntimeException("connect error", channelFuture.cause());
            }

            Channel channel = channelFuture.channel();

//            Channel channel = b.connect(host, port).sync().channel();
            return channel;
            //.channel().closeFuture().sync();
        } catch (Throwable e) {
//            logger.error("can not connect to server.", e);
//            e.printStackTrace();
            throw new RuntimeException("can not connect to server " + host + ":" + port, e);
        } finally {
//            group.shutdownGracefully();
        }
    }

    //working connection
    public static Channel connectWork(String host, int port) {
        return connect(host, port);
    }

    //local connection
    public static Channel connectLocal(String host, int port, ChannelHandler... handlers) {
        return connect(host, port, handlers);
    }

}
